<template>
  <div>
    <a-button v-if="!record" type="primary" @click="dialog = true" class="mb-4">设置延期</a-button>
    <a v-else @click="dialog = true">查看</a>
    <a-modal v-model="dialog" :title="record ? '详情' : '设置延期'" :width="950">
      <a-form-model
        ref="form"
        :model="form"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
        :hideRequiredMark="true"
      >
        <div class="grid grid-cols-2">
          <a-form-model-item label="项目地址：" prop="addr">
            <a-select
              show-search
              option-filter-prop="children"
              :filter-option="filterOption"
              @change="Onchange"
              v-model="form.addr"
              :disabled="readOnly && record ? true : false"
            >
              <a-select-option :value="item.projectId" v-for="item in projectList" :key="item.projectId">
                {{ item.addr }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="延期本金金额：" prop="loanAddPrincipalAfter">
            <m-input-number
              v-model="form.loanAddPrincipalAfter"
              :disabled="readOnly && record ? true : false"
              class="length"
            />
          </a-form-model-item>
        </div>
        <div class="grid grid-cols-2">
          <a-form-model-item label="项目延期申请时间：" prop="applyDate">
            <a-date-picker v-model="form.applyDate" :disabled="readOnly && record ? true : false" />
          </a-form-model-item>
          <a-form-model-item label="延期资金成本：" prop="loanAddCapitalAfter">
            <m-input-number
              v-model="form.loanAddCapitalAfter"
              :disabled="readOnly && record ? true : false"
              class="length"
            />
          </a-form-model-item>
        </div>
        <div class="grid grid-cols-2">
          <a-form-model-item label="延期时间段：" prop="dateRange">
            <a-range-picker v-model="dateRange" :disabled="readOnly && record ? true : false" />
          </a-form-model-item>
          <a-form-model-item label="利息利率：" prop="delayRate">
            <a-input
              v-model="form.delayRate"
              addon-after="%"
              @change="form.delayRate = form.delayRate.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
              :disabled="readOnly && record ? true : false"
            >
              <a-select
                prop="delayRateUnit"
                slot="addonBefore"
                v-model="form.delayRateUnit"
                :disabled="readOnly && record ? true : false"
              >
                <a-select-option :value="item.value" v-for="item in rateTypes" :key="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-input>
          </a-form-model-item>
        </div>
        <div class="grid grid-cols-2">
          <a-form-model-item label="贷款限额费：" prop="limitRate">
            <m-input v-model="form.limitRate" :disabled="readOnly && record ? true : false" />
          </a-form-model-item>
          <a-form-model-item label="贷款限额费付款方式：" prop="limitPayType">
            <a-select v-model="form.limitPayType" :disabled="readOnly && record ? true : false">
              <a-select-option :value="2">
                月付
              </a-select-option>
              <a-select-option :value="3">
                每月资本化
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </div>
        <div class="grid grid-cols-2">
          <a-form-model-item label="出借人手续费：" prop="commissionRate">
            <m-input v-model="form.commissionRate" :disabled="readOnly && record ? true : false" />
          </a-form-model-item>
          <a-form-model-item label="出借人手续费付款方式：" prop="commissionPayType">
            <a-select v-model="form.commissionPayType" :disabled="readOnly && record ? true : false">
              <a-select-option :value="1">
                立即付
              </a-select-option>
              <a-select-option :value="4">
                立即资本化
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </div>
        <div class="grid grid-cols-2">
          <a-form-model-item label="其他费用：" prop="otherAmount">
            <a-input v-model="form.otherAmount" :disabled="readOnly && record ? true : false" />
          </a-form-model-item>
          <a-form-model-item label="其他费用付款方式：" prop="otherPayType">
            <a-select v-model="form.otherPayType" :disabled="readOnly && record ? true : false">
              <a-select-option :value="item.value" v-for="item in otherType" :key="item.text">
                {{ item.text }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </div>
        <div class="grid grid-cols-2">
          <a-form-model-item label="其他费用说明：" prop="otherFeeInstruction">
            <a-input v-model="form.otherFeeInstruction" :disabled="readOnly && record ? true : false" />
          </a-form-model-item>
        </div>
        <div class="grid grid-cols-2">
          <a-form-model-item label="退出费：" prop="exitRate">
            <m-input v-model="form.exitRate" :disabled="readOnly && record ? true : false" />
          </a-form-model-item>
          <a-form-model-item label="行政费：" prop="administrativeRate">
            <m-input v-model="form.administrativeRate" :disabled="readOnly && record ? true : false" />
          </a-form-model-item>
        </div>
        <div class="grid grid-cols-2">
          <a-form-model-item label="报价利率：">
            <a-input disabled :value="quotationRate" />
          </a-form-model-item>
        </div>
      </a-form-model>
      <template slot="footer">
        <a-button v-if="!record" key="back" @click="dialog = false">
          取消
        </a-button>
        <a-button v-else-if="Archive != 1" type="primary" @click="change" v-action:update>修改</a-button>
        <a-button v-if="!record" key="submit" type="primary" @click="submit">
          确定
        </a-button>
        <a-button v-else-if="Archive != 1" type="primary" @click="update" v-action:update>保存</a-button>
      </template>
    </a-modal>
  </div>
</template>
<script>
import { unit, rateTypes, otherType } from '@/dict'
import { getAddr, getDetailList, creatLoanDelay, updataloanDelay, getloanDelay, createHistory } from '@/api/common'
import NP from 'number-precision'
import moment from 'moment'
import { commonRule, dateRule } from '@/utils/rules'
export default {
  name: 'addDelay',
  props: ['record'],
  data() {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 12 },
      dialog: false,
      readOnly: true,
      unit,
      rateTypes,
      otherType,
      dateRange: [null, null],
      form: {
        projectId: '',
        addr: '',
        loanAddPrincipalAfter: '',
        applyDate: '',
        loanAddCapitalAfter: '',
        delayStartDate: '',
        delayEndDate: '',
        delayRate: '',
        delayRateUnit: 3,
        limitDay: '',
        limitRate: '',
        limitPayType: 2,
        commissionRate: '',
        commissionPayType: 1,
        otherAmount: '',
        otherPayType: 1,
        otherFeeInstruction: '',
        exitRate: '',
        administrativeRate: ''
      },
      rules: {
        addr: commonRule,
        loanAddPrincipalAfter: commonRule,
        applyDate: dateRule,
        loanAddCapitalAfter: dateRule,
        delayRate: commonRule,
        delayRateUnit: commonRule,
        limitRate: commonRule,
        commissionRate: commonRule,
        otherAmount: commonRule,
        otherFeeInstruction: commonRule,
        exitRate: commonRule,
        administrativeRate: commonRule
      },
      projectList: [],
      Archive: 0,
      limitCalcType: 0
    }
  },
  watch: {
    form: {
      handler(v) {
        const _form = Object.assign({}, this.form)
        _form.applyDate = _form.applyDate ? _form.applyDate.format('X') : null
        this.dateRange ? (_form.dateRange = [this.dateRange[0].format('X'), this.dateRange[1].format('X')]) : null
        this.$store.commit('form/SAVE_DATA', {
          key: 'addDelay',
          value: _form
        })
      },
      deep: true
    },
    dialog(v) {
      if (this.dialog) {
        this.getData()
      }
      if (this.record) {
        this.getDatas()
      }
      if (this.dialog && !this.record) {
        const formStore = this.$store.state.form?.['addDelay']
        console.log(formStore)
        if (formStore) {
          formStore.applyDate && (formStore.applyDate = moment(formStore.applyDate, 'X'))
          this.dateRange = formStore.dateRange
            ? [moment(formStore.dateRange[0], 'X'), moment(formStore.dateRange[1], 'X')]
            : [null, null]
          // formStore.delayStartDate && (formStore.delayStartDate = moment(formStore.delayStartDate, 'X'))
          // formStore.delayEndDate && (formStore.delayEndDate = moment(formStore.delayEndDate, 'X'))
          formStore && Object.assign(this.form, formStore)
        }
      }
    }
  },
  computed: {
    //报价利率
    quotationRate() {
      const b = NP.plus(this.form.commissionRate, this.form.exitRate)
      var a = `${this.form.delayRate}% + ${this.form.limitRate}% + ${b}%`
      return a
    }
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    change() {
      this.readOnly = false
    },
    async getData() {
      const res = await getAddr()
      this.projectList = res.result.data
    },
    async getDatas() {
      const id = this.record.projectId
      const r = await getDetailList(id)
      this.limitCalcType = r.result.data.loanData?.limitCalcType
      this.Archive = r.result.data.Archive
      const form = {
        id: this.record.id
      }
      const res = await getloanDelay(form)
      const _form = res.result.data.list[0]
      for (let k in this.form) {
        this.form[k] = _form[k]
      }
      this.form.applyDate = moment(this.form.applyDate * 1000)
      this.form.loanAddPrincipalAfter = _form.principal
      this.form.loanAddCapitalAfter = _form.capital
      this.dateRange[0] = moment(_form.delayStartDate * 1000)
      this.dateRange[1] = moment(_form.delayEndDate * 1000)
    },
    async submit() {
      const form = Object.assign({}, this.form)
      const valid = await this.$refs.form.validate()
      if (!valid) return
      form.applyDate = Number(form.applyDate.startOf('day').format('X'))
      form.delayStartDate = Number(this.dateRange[0].startOf('day').format('X'))
      form.limitStartDate = Number(this.dateRange[0].startOf('day').format('X'))
      form.otherStartDate = Number(this.dateRange[0].startOf('day').format('X'))
      form.otherDay = moment(this.dateRange[0]).date()
      form.delayEndDate = Number(this.dateRange[1].startOf('day').format('X'))
      form.delayRate = Number(form.delayRate)
      if (this.limitCalcType == 1) {
        form.limitDay = 1
      } else {
        form.limitDay = Number(moment(form.limitStartDate * 1000).date())
      }
      await creatLoanDelay(form)
      this.$store.commit('form/CLEAR', 'addDelay')
      this.$emit('update')
      this.dialog = false
      // this.form = {}
    },
    async update() {
      const form = Object.assign({}, this.form)
      const valid = await this.$refs.form.validate()
      if (!valid) return
      form.applyDate = Number(form.applyDate.startOf('day').format('X'))
      form.delayStartDate = Number(this.dateRange[0].startOf('day').format('X'))
      form.limitStartDate = Number(this.dateRange[0].startOf('day').format('X'))
      form.otherStartDate = Number(this.dateRange[0].startOf('day').format('X'))
      form.otherDay = moment(this.dateRange[0]).date()
      form.delayEndDate = Number(this.dateRange[1].startOf('day').format('X'))
      form.delayRate = Number(form.delayRate)
      if (this.limitCalcType == 1) {
        form.limitDay = 1
      } else {
        form.limitDay = Number(moment(form.limitStartDate * 1000).date())
      }
      await updataloanDelay(this.record.id, form)
      this.readOnly = true
      const history = {
        recordType: 3,
        tableId: Number(this.record.id)
      }
      await createHistory(history)
      this.$emit('update')
      this.dialog = false
    },
    async Onchange(v) {
      const choose = this.projectList.find(el => el.projectId == v)
      // console.log(choose)
      this.form.projectId = choose.projectId
      const res = await getDetailList(this.form.projectId)
      const _form = res.result.data
      this.form.loanAddPrincipalAfter = _form.loanAddPrincipalAfter
      this.form.loanAddCapitalAfter = _form.loanAddCapitalAfter
      this.limitCalcType = _form?.loanData?.limitCalcType
    }
  }
}
</script>
<style lang="css" scoped>
.length {
  width: 200px;
}
</style>
